package gc3d.servlet;

import gc3d.database.DBSettings;
import gc3d.database.GridPovDB;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;


public class taskUpdate extends HttpServlet{

	private static final long serialVersionUID = 1L;


	public void doGet(HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException {
		PrintWriter out = res.getWriter();

		//String jobIDsString = req.getParameter("jobIDs");
		String[] taskIDs = new String[0];
		//if(jobIDsString != null){
		//	jobIDs = jobIDsString.split(";");
		//}
		String taskIDsString = "";
		//out.println("<p>jobs:</p>");
		GridPovDB db;
		
		
		
		try {
			db = new GridPovDB(DBSettings.getDBURL(),DBSettings.getDBuser(),DBSettings.getDBpass());
			//ResultSet rs = db.query("SELECT task_id from tasks;");
		    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			ResultSet rs = db.query("select jobs.task_id, tasks.start_time, tasks.finish_time, tasks.name, count(jobs.frame_number) as jobs, count(distinct jobs.node_id) as nodes, count(jobs.finish_time) as jobs_finished from jobs,tasks where jobs.task_id = tasks.task_id group by task_id,name, tasks.start_time, tasks.finish_time order by tasks.start_time desc");
			JSONArray taskList = new JSONArray(); 
			while( rs.next() ){
				
				JSONObject task = new JSONObject();
				
				task.put("id",rs.getString("task_id"));
				task.put("name",rs.getString("name"));
				task.put("start_time",sdf.format(rs.getTimestamp("start_time").getTime()));
				//task.put("start_time",rs.getString("start_time"));
				if (rs.getDate("finish_time") != null){ 
					task.put("finish_time",rs.getTimestamp("finish_time").toString());
				} else {
					task.put("finish_time","");
				}
				task.put("nodes",rs.getString("nodes"));
				task.put("tasks_completed",rs.getString("jobs_finished"));
				task.put("tasks",rs.getString("jobs"));
				
				taskList.add(task);
				
				
			}
			out.print(taskList);
		} catch (ClassNotFoundException e1) {
			out.println("ClassNotFoundExceptio");
			// TODO Auto-generated catch block
			out.println(e1.getMessage());
		} catch (SQLException e1) {
			out.println("SQLException");
			// TODO Auto-generated catch block
			out.println(e1.getMessage());
		}
	}
}
